/*
 * @Description: 每一个阶段种各个情感的最具有代表性的书籍展示
 * @Author: zy
 * @Date: 2020-12-18 15:02:24
 * @LastEditors: Wuyi
 * @LastEditTime: 2021-04-12 20:19:18
 */
import * as d3 from 'd3'
export class Grade {
  color = d3.scaleOrdinal(d3.schemeCategory10)

  constructor (divId) {
    this.divId = divId
    this.initChart()
  }

  initChart () {
    this.chart = {}
    this.chart.padding = {
      left: 10,
      right: 10,
      top: 10,
      bottom: 10
    }
    this.chart.divHeight = document.getElementById(this.divId).offsetHeight -
          this.chart.padding.top -
          this.chart.padding.bottom
    this.chart.divWidth = document.getElementById(this.divId).offsetWidth -
          this.chart.padding.left -
          this.chart.padding.right

    this.chart.svg = d3
      .select('#' + this.divId)
      .append('svg')
      .attr('width', this.chart.divWidth +
        this.chart.padding.left +
        this.chart.padding.right
      )
      .attr('height', this.chart.divHeight +
        this.chart.padding.top +
        this.chart.padding.bottom
      )
      .attr('class', 'svg_chart')
  }

  setData (data) {
    this.data = data
  }

  computeLayOut () {
    const height = this.chart.divHeight / this.data.length
    this.chart.itemHeight = height
    this.chart.rectHeight = height * 0.95
    this.chart.rectPadding = height * 0.1
  }

  render () {
    this.computeLayOut()
    let books = this.chart.svg.selectAll('.book')
      .data(this.data)

    let bookEnter = books.enter()
      .append('g')
      .attr('class', 'book')
      .attr('transform', 'translate(10)')

    bookEnter.append('rect')
      .attr('x', this.chart.padding.left)
      .attr('y', (_, i) => this.chart.padding.top + i * this.chart.itemHeight)
      .attr('width', this.chart.divWidth * 0.95)
      .attr('height', this.chart.rectHeight)
      .attr('fill', (_, i) => this.color(i))
      // .transition()
      // .duration(1000)
      // .delay((_, i) => 1000 * i)
      // .attr('fill', (_, i) => this.color(i + 1))
      .style('stroke', (_, i) => this.color(i))
      .style('stroke-width', 1)
      .on('click', function (event, d) {
        console.log(d)
      })
      // .on('mouseover', function (event, d) {
      //   d.oldColor = d3.select(this).attr('fill')
      //   console.log(d.oldColor)
      //   d3.select(this)
      //     .attr('fill', 'red')
      // })
      // .on('mouseout', function (event, d) {
      //   console.log(d)
      //   d3.select(this)
      //     .transition()
      //     .duration(500)
      //     .attr('fill', function (x) {
      //       return d.oldColor
      //     })
      // })

    bookEnter.append('text')
      .attr('x', this.chart.padding.left + 5)
      .attr('y', (_, i) => this.chart.padding.top + i * this.chart.itemHeight + this.chart.rectHeight * 0.7)
      .text(d => d.bookName)
      .attr('font-size', 10)
  }
}
